package com.blb.permission_ms.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.blb.permission_ms.entity.Permission;
import com.blb.permission_ms.entity.Role;
import com.blb.permission_ms.entity.User;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserMapper extends BaseMapper<User> {

    @Select("select r.* from role r join user_role ur\n" +
            "on r.id = ur.role_id\n" +
            "join user u \n" +
            "on u.id = ur.user_id\n" +
            "where u.username = #{username}")
    List<Role> selectRolesByUsername(String username);

    @Select("select p.* from permission p join role_permission rp \n" +
            "on p.id = rp.permission_id\n" +
            "join role r on r.id = rp.role_id\n" +
            "join user_role ur on r.id = ur.role_id\n" +
            "join user u on ur.user_id = u.id\n" +
            "where u.username = #{username}")
    List<Permission> selectPermissionByUsername(String username);

    /**
     * 查询权限菜单，权限有上下级关系
     * @param username
     * @return
     */
    @Results(id = "permissionMap",value = {
            @Result(property = "id",column = "id",id = true),
            @Result(property = "name",column = "name"),
            @Result(property = "description",column = "description"),
            @Result(property = "url",column = "url"),
            @Result(property = "icon",column = "icon"),
            @Result(property = "sort",column = "sort"),
            @Result(property = "pid",column = "pid"),
            @Result(property = "childPermissions",
                    many = @Many(select = "com.blb.permission_ms.mapper.PermissionMapper.selectPermissionsByPid"),column = "id")
    })
    @Select("select p.* from permission p join role_permission rp \n" +
            "on p.id = rp.permission_id\n" +
            "join role r on r.id = rp.role_id\n" +
            "join user_role ur on r.id = ur.role_id\n" +
            "join user u on ur.user_id = u.id\n" +
            "where u.username = #{username} and p.pid = 1")
    List<Permission> selectPermissionMenuByUsername(String username);
}
